package com.ojoin.trade.supplyloan_core.utils.catchdata.httpclient;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ojoin.trade.common.Constants;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.WaitUtil;

public class HttpClientUtil {

	private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);

	public static CloseableHttpClient getHttpClientLoged(String logurl,
			String logedurl, Set<Cookie> cookies) {

		 CloseableHttpClient httpclient = getHttpClientByCookies(cookies);

		//CloseableHttpClient httpclient = getHttpclient();

		HttpGet request = new HttpGet(logedurl);
		// HttpUriRequest request = RequestBuilder.get(logedurl).build();

		try {
			CloseableHttpResponse response = httpclient.execute(request);

			// httpclient.
			LogUtils.info(log, response.getStatusLine().getStatusCode() + "");
			LogUtils.info(log, getContent(response));

			WaitUtil.waitTimeSeconds(2);
			
			CloseableHttpResponse response2 = httpclient.execute(request);

			// httpclient.
			LogUtils.info(log, response2.getStatusLine().getStatusCode() + "");
			LogUtils.info(log, getContent(response2));
			/*HttpClientContext context = HttpClientContext.create();

			Registry<CookieSpecProvider> registry = RegistryBuilder
					.<CookieSpecProvider> create()
					.register(CookieSpecs.BEST_MATCH,
							new BestMatchSpecFactory())
					.register(CookieSpecs.BROWSER_COMPATIBILITY,
							new BrowserCompatSpecFactory()).build();
			context.setCookieSpecRegistry(registry);

			context.setCookieStore(getCookiesBySet(cookies));

			CloseableHttpResponse response2 = httpclient.execute(request,
					context);

			LogUtils.info(log, response2.getStatusLine().getStatusCode() + "");
			LogUtils.info(log, getContent(response2));*/

			
		} catch (ClientProtocolException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}

		return httpclient;

	}

	public static boolean isredirect(CloseableHttpResponse response) {
		int statuscode = response.getStatusLine().getStatusCode();

		if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
				|| (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
				|| (statuscode == HttpStatus.SC_SEE_OTHER)
				|| (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
			return true;
		}

		return false;
	}

	public static String getDrectUrl(CloseableHttpResponse response) {
		int statuscode = response.getStatusLine().getStatusCode();

		if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
				|| (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
				|| (statuscode == HttpStatus.SC_SEE_OTHER)
				|| (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {

			Header[] heads = response.getHeaders("location");

			String locationURL = heads[0].toString();

			locationURL = locationURL.substring(10);

			return locationURL;

		}

		return null;
	}

	public static String getContent(CloseableHttpResponse response) {

		HttpEntity entity = response.getEntity();
		LogUtils.info(log, "----------------------------------------");
		LogUtils.info(log, response.getStatusLine() + "");
		if (entity != null) {
			LogUtils.info(log,
					"Response content length: " + entity.getContentLength());
			try {
				return EntityUtils.toString(entity);
			} catch (ParseException e) {
				
				e.printStackTrace();
			} catch (IOException e) {
				
				e.printStackTrace();
			}
		}

		return null;

	}

	public static BasicCookieStore getCookiesBySet(Set<Cookie> cookies) {
		BasicCookieStore cookieStore = new BasicCookieStore();

		Iterator<Cookie> it = cookies.iterator();

		while (it.hasNext()) {
			Cookie co = it.next();

			cookieStore.addCookie(co);
		}

		return cookieStore;
	}

	public static CloseableHttpClient getHttpClientByCookies(Set<Cookie> cookies) {
		BasicCookieStore cookieStore = getCookiesBySet(cookies);

		CloseableHttpClient httpclient = HttpClients.custom()
				.setDefaultCookieStore(cookieStore).build();

		return httpclient;
	}

	public static CloseableHttpClient getHttpclient() {

		BasicCookieStore cookieStore = new BasicCookieStore();

		CloseableHttpClient httpclient = HttpClients.custom()
				.setDefaultCookieStore(cookieStore).build();

		return httpclient;
	}

	public static boolean loginByPos(CloseableHttpClient httpcilent,
			String url, Map<String, String> map, String charset) {

		boolean flag = false;
		CloseableHttpResponse response2 = null;

		try {
			HttpUriRequest login = RequestBuilder
					.post()
					.setUri(url)
					.addParameter("j_username", "GO-11002392")
					.addParameter("j_password", "htwj2013")
					.addParameter("lt",
							"LT-1352356-OAHbdbTK7JFlEbLgfTjgnNLWUfN6DJ")
					.addParameter("execution", "e1s1")
					.addParameter("_eventId", "submit")
					.addParameter("logtype", "1").build();

			// logger.info("executing request " + login.getURI());
			response2 = httpcilent.execute(login);
			/*
			 * Header[] header = response2.getAllHeaders(); if(null != header){
			 * for(int i=0;i<header.length;i++){ logger.info(header[i]); } }
			 */
			// HttpEntity entity2 = response2.getEntity();
			// String str2 = EntityUtils.toString(entity2, "UTF-8");
			// logger.info(str2);

			// logger.info(response2.)

			int statusCode = response2.getStatusLine().getStatusCode();

			/*
			 * List<Cookie> cookies =
			 * MyMainClient.getCookieStore().getCookies(); if
			 * (cookies.isEmpty()) { logger.info("None"); } else { for (int i =
			 * 0; i < cookies.size(); i++) { logger.info(cookies.get(i)); } }
			 */

			if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
					|| statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {

				if (response2.getHeaders("location").length > 0) {
					/*
					 * Header[] h = response2.getHeaders("location") ; for(int
					 * i=0;i<h.length;i++){ logger.info(h[i]); }
					 */
					String locationURL = response2.getHeaders("location")[0]
							.toString();
					// logger.info(locationURL);
					locationURL = locationURL.substring(10);
					// logger.info(locationURL);
					// URL url = new URL(locationURL);
					// URI uri3 = new URI(locationURL);

					response2.close();
					// URI uri2 = new URI(url.getProtocol(), url.getHost(),
					// url.getPath(), url.getQuery(), null);
					return loginByGet(httpcilent, locationURL, charset);
				}

			} else {
				HttpEntity entity = response2.getEntity();
				if (entity != null) {
					String str = EntityUtils.toString(entity, Constants.ENCODING);
					log.info(str);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != response2) {
				try {
					response2.close();
				} catch (IOException e) {
					
					e.printStackTrace();
				}
			}

		}
		return flag;
	}

	public static boolean loginByGet(CloseableHttpClient httpClient,
			String url, String charset) {
		// HttpClient httpClient = null;
		boolean flag = true;
		HttpGet httpGet = null;
		HttpResponse response = null;
		try {
			// httpClient = new SSLClient();
			httpGet = new HttpGet(url);
			// 设置参数

			response = httpClient.execute(httpGet);

			if (null != response) {
				int statuscode = response.getStatusLine().getStatusCode();
				if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
						|| (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
						|| (statuscode == HttpStatus.SC_SEE_OTHER)
						|| (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {// 读取新的URL地址

					Header[] heads = response.getHeaders("location");

					String locationURL = heads[0].toString();

					locationURL = locationURL.substring(10);

					loginByGet(httpClient, locationURL, charset);

					// Header header = httpPost.getResponseHeader("location");
				} else {

					Header[] heads = response.getHeaders("location");
					flag = true;

					HttpEntity entity = response.getEntity();
					if (entity != null) {
						String str = EntityUtils.toString(entity, Constants.ENCODING);
						log.info(str);
					}
				}

			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return flag;
	}

	public static HttpResponse doPostReturnResponse(HttpClient httpClient,
			String url, Map<String, String> map, String charset) {
		// HttpClient httpClient = null;
		HttpPost httpPost = null;
		HttpResponse response = null;
		try {
			// httpClient = new SSLClient();
			httpPost = new HttpPost(url);
			// 设置参数
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			Iterator<Entry<String, String>> iterator = map.entrySet()
					.iterator();
			while (iterator.hasNext()) {
				Entry<String, String> elem = (Entry<String, String>) iterator
						.next();
				list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
			}
			if (list.size() > 0) {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,
						charset);
				httpPost.setEntity(entity);
			}

			response = httpClient.execute(httpPost);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return response;
	}

	public static String doPost(HttpClient httpClient, String url,
			Map<String, String> map, String charset) {
		// HttpClient httpClient = null;
		HttpPost httpPost = null;
		String result = null;
		try {
			// httpClient = new SSLClient();
			httpPost = new HttpPost(url);
			// 设置参数
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			Iterator<Entry<String, String>> iterator = map.entrySet()
					.iterator();
			while (iterator.hasNext()) {
				Entry<String, String> elem = (Entry<String, String>) iterator
						.next();
				list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
			}
			if (list.size() > 0) {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,
						charset);
				httpPost.setEntity(entity);
			}

			HttpResponse response = httpClient.execute(httpPost);

			if (response != null) {
				StatusLine statuesLine = response.getStatusLine();

				LogUtils.info(log, statuesLine.toString());

				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {

					result = EntityUtils.toString(resEntity, charset);
					LogUtils.info(log, result);
				}
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	public String doPost(String url, Map<String, String> map, String charset) {
		HttpClient httpClient = null;
		HttpPost httpPost = null;
		String result = null;
		try {
			httpClient = new SSLClient();
			httpPost = new HttpPost(url);
			// 设置参数
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			Iterator<Entry<String, String>> iterator = map.entrySet()
					.iterator();
			while (iterator.hasNext()) {
				Entry<String, String> elem = (Entry<String, String>) iterator
						.next();
				list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
			}
			if (list.size() > 0) {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,
						charset);
				httpPost.setEntity(entity);
			}

			HttpResponse response = httpClient.execute(httpPost);
			if (response != null) {
				StatusLine statuesLine = response.getStatusLine();
				LogUtils.info(log, statuesLine.toString());

				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, charset);
				}
			}

			httpClient.getConnectionManager().shutdown();

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	public String doGet(String url, String charset) {
		HttpClient httpClient = null;
		HttpGet httpGet = null;
		String result = null;
		try {
			httpClient = new SSLClient();
			httpGet = new HttpGet(url);
			// 设置参数
			List<NameValuePair> list = new ArrayList<NameValuePair>();

			HttpResponse response = httpClient.execute(httpGet);
			if (response != null) {
				StatusLine statuesLine = response.getStatusLine();
				LogUtils.info(log, statuesLine.toString());

				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, charset);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	public static String doGet(HttpClient httpClient, String url, String charset) {
		// HttpClient httpClient = null;
		HttpGet httpGet = null;
		String result = null;
		try {
			// httpClient = new SSLClient();
			httpGet = new HttpGet(url);
			// 设置参数

			HttpResponse response = httpClient.execute(httpGet);
			if (response != null) {
				StatusLine statuesLine = response.getStatusLine();
				LogUtils.info(log, statuesLine.toString());

				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, charset);

					LogUtils.info(log, result);

				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	public byte[] doGetRetunByte(String url, String charset) {
		HttpClient httpClient = null;
		HttpGet httpGet = null;
		byte[] result = null;
		try {
			httpClient = new SSLClient();
			httpGet = new HttpGet(url);
			// 设置参数
			List<NameValuePair> list = new ArrayList<NameValuePair>();

			HttpResponse response = httpClient.execute(httpGet);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toByteArray(resEntity);

				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

}
